package orz.itrip.trade.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.web.bind.annotation.*;
import orz.itrip.DtoUtils;
import orz.itrip.dto.Dto;
import orz.itrip.pojo.HotelOrder;
import orz.itrip.trade.config.AlipayConfig;
import orz.itrip.trade.service.GetInstanceService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
@RequestMapping("/api/")
public class AlipayController {
    @Resource
    private GetInstanceService getInstance;
    @GetMapping(value = "prepay/{orderNo}",produces = "text/html;charset=UTF-8")
    public String getOrderByOid(@PathVariable("orderNo") String orderNo) throws UnsupportedEncodingException {
        HotelOrder hotelOrder = getInstance.getHotelOrder(orderNo);
        //根据订单ID查询出订单的相关信息，返回给页面
        String str =
                "<!DOCTYPE html>\n" +
                "<html>\n" +
                "\t<head>\n" +
                "\t<title>支付宝手机网站支付接口</title>\n" +
                "\t<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n" +
                "<style>\n" +
                "    *{\n" +
                "        margin:0;\n" +
                "        padding:0;\n" +
                "    }\n" +
                "    ul,ol{\n" +
                "        list-style:none;\n" +
                "    }\n" +
                "    body{\n" +
                "        font-family: \"Helvetica Neue\",Helvetica,Arial,\"Lucida Grande\",sans-serif;\n" +
                "    }\n" +
                "    .hidden{\n" +
                "        display:none;\n" +
                "    }\n" +
                "    .new-btn-login-sp{\n" +
                "        padding: 1px;\n" +
                "        display: inline-block;\n" +
                "        width: 75%;\n" +
                "    }\n" +
                "    .new-btn-login {\n" +
                "        background-color: #02aaf1;\n" +
                "        color: #FFFFFF;\n" +
                "        font-weight: bold;\n" +
                "        border: none;\n" +
                "        width: 100%;\n" +
                "        height: 30px;\n" +
                "        border-radius: 5px;\n" +
                "        font-size: 16px;\n" +
                "    }\n" +
                "    #main{\n" +
                "        width:100%;\n" +
                "        margin:0 auto;\n" +
                "        font-size:14px;\n" +
                "    }\n" +
                "    .red-star{\n" +
                "        color:#f00;\n" +
                "        width:10px;\n" +
                "        display:inline-block;\n" +
                "    }\n" +
                "    .null-star{\n" +
                "        color:#fff;\n" +
                "    }\n" +
                "    .content{\n" +
                "        margin-top:5px;\n" +
                "    }\n" +
                "    .content dt{\n" +
                "        width:100px;\n" +
                "        display:inline-block;\n" +
                "        float: left;\n" +
                "        margin-left: 20px;\n" +
                "        color: #666;\n" +
                "        font-size: 13px;\n" +
                "        margin-top: 8px;\n" +
                "    }\n" +
                "    .content dd{\n" +
                "        margin-left:120px;\n" +
                "        margin-bottom:5px;\n" +
                "    }\n" +
                "    .content dd input {\n" +
                "        width: 85%;\n" +
                "        height: 28px;\n" +
                "        border: 0;\n" +
                "        -webkit-border-radius: 0;\n" +
                "        -webkit-appearance: none;\n" +
                "    }\n" +
                "    #foot{\n" +
                "        margin-top:10px;\n" +
                "        position: absolute;\n" +
                "        bottom: 15px;\n" +
                "        width: 100%;\n" +
                "    }\n" +
                "    .foot-ul{\n" +
                "        width: 100%;\n" +
                "    }\n" +
                "    .foot-ul li {\n" +
                "        width: 100%;\n" +
                "        text-align:center;\n" +
                "        color: #666;\n" +
                "    }\n" +
                "    .note-help {\n" +
                "        color: #999999;\n" +
                "        font-size: 12px;\n" +
                "        line-height: 130%;\n" +
                "        margin-top: 5px;\n" +
                "        width: 100%;\n" +
                "        display: block;\n" +
                "    }\n" +
                "    #btn-dd{\n" +
                "        margin: 20px;\n" +
                "        text-align: center;\n" +
                "    }\n" +
                "    .foot-ul{\n" +
                "        width: 100%;\n" +
                "    }\n" +
                "    .one_line{\n" +
                "        display: block;\n" +
                "        height: 1px;\n" +
                "        border: 0;\n" +
                "        border-top: 1px solid #eeeeee;\n" +
                "        width: 100%;\n" +
                "        margin-left: 20px;\n" +
                "    }\n" +
                "    .am-header {\n" +
                "        display: -webkit-box;\n" +
                "        display: -ms-flexbox;\n" +
                "        display: box;\n" +
                "        width: 100%;\n" +
                "        position: relative;\n" +
                "        padding: 7px 0;\n" +
                "        -webkit-box-sizing: border-box;\n" +
                "        -ms-box-sizing: border-box;\n" +
                "        box-sizing: border-box;\n" +
                "        background: #1D222D;\n" +
                "        height: 50px;\n" +
                "        text-align: center;\n" +
                "        -webkit-box-pack: center;\n" +
                "        -ms-flex-pack: center;\n" +
                "        box-pack: center;\n" +
                "        -webkit-box-align: center;\n" +
                "        -ms-flex-align: center;\n" +
                "        box-align: center;\n" +
                "    }\n" +
                "    .am-header h1 {\n" +
                "        -webkit-box-flex: 1;\n" +
                "        -ms-flex: 1;\n" +
                "        box-flex: 1;\n" +
                "        line-height: 18px;\n" +
                "        text-align: center;\n" +
                "        font-size: 18px;\n" +
                "        font-weight: 300;\n" +
                "        color: #fff;\n" +
                "    }\n" +
                "</style>\n" +
                "</head>\n" +
                "<body text=#000000 bgColor=\"#ffffff\" leftMargin=0 topMargin=4>\n" +
                "<header class=\"am-header\">\n" +
                "        <h1>确认订单信息</h1>\n" +
                "</header>\n" +
                "<div id=\"main\">\n" +
                "        <form name=alipayment action='../pay' method=\"post\">\n" +
                "            <div id=\"body\" style=\"clear:left\">\n" +
                "                <dl class=\"content\">\n" +
                "                    <dt>订单编号：</dt>\n" +
                "                    <dd>\n" + hotelOrder.getOrderNo() +
                "                        <input type=\"hidden\" id=\"WIDout_trade_no\" name=\"WIDout_trade_no\" value=\""+hotelOrder.getOrderNo()+"\">\n" +
                "                        <input type=\"hidden\" name=\"WIDsubject\" value=\""+hotelOrder.getHotelName()+"\">\n" +
                "                        <input type=\"hidden\" name=\"WIDtotal_amount\" value=\""+hotelOrder.getPayAmount()+"\">\n" +
                "                    </dd>\n" +
                "                    <hr class=\"one_line\">\n" +
                "                    <dt>酒店名称：</dt>\n" +
                "                    <dd>\n" + hotelOrder.getHotelName() +
                "                    </dd>\n" +
                "                    <hr class=\"one_line\">\n" +
                "                    <dt>付款金额：</dt>\n" +
                "                    <dd>\n" + hotelOrder.getPayAmount()+
                "                    </dd>\n" +
                "                    <hr class=\"one_line\"/>\n" +
                "                    <dt>订房描述：</dt>\n" +hotelOrder.getSpecialRequirement()+
                "                    <dd>\n" +
                "                        \t房间ID："+hotelOrder.getRoomId()+",数量："+hotelOrder.getCount()+"\n" +
                "                    </dd>\n" +
                "                    <hr class=\"one_line\">\n" +
                "                    <dt></dt>\n" +
                "                    <dd id=\"btn-dd\">\n" +
                "                        <span class=\"new-btn-login-sp\">\n" +
                "                            <button class=\"new-btn-login\" type=\"submit\" style=\"text-align:center;\">确 认</button>\n" +
                "                        </span>\n" +
                "                        <span class=\"note-help\">如果您点击“确认”按钮，即表示您同意该次的执行操作。</span>\n" +
                "                    </dd>\n" +
                "                </dl>\n" +
                "            </div>\n" +
                "\t\t</form>\n" +
                "        <div id=\"foot\">\n" +
                "\t\t\t<ul class=\"foot-ul\">\n" +
                "\t\t\t\t<li>\n" +
                "\t\t\t\t\t版权信息\n" +
                "\t\t\t\t</li>\n" +
                "\t\t\t</ul>\n" +
                "\t\t</div>\n" +
                "\t</div>\n" +
                "</body>\n" +
                "\n" +
                "</html>";
        return str;
    }
    @PostMapping("pay")
    public void sendMsgToAli(HttpServletResponse response,HttpServletRequest request) throws AlipayApiException, IOException {
        HotelOrder hotelOrder = getInstance.getHotelOrder(request.getParameter("WIDout_trade_no"));

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = hotelOrder.getOrderNo();
        //付款金额，必填
        String total_amount = hotelOrder.getPayAmount().toString();
        //订单名称，必填
        String subject = hotelOrder.getHotelName();
        //商品描述，可空
        String body = null;

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        response.setContentType("text/html;charset=utf-8");
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        System.out.println("***************\n"+result+"\n*********************");
        //输出
        response.getWriter().println(result);
    }

    @PostMapping("notifyUrl")
    public void notifyUrl(HttpServletRequest request, HttpServletResponse response) throws AlipayApiException, IOException {

        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, "UTF-8",AlipayConfig.sign_type); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——

        /* 实际验证过程建议商户务必添加以下校验：
        1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
        2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
        3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
        4、验证app_id是否为该商户本身。
        */
        if(signVerified) {//验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

            System.out.println(trade_status);

            if(trade_status.equals("TRADE_FINISHED")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            }else if (trade_status.equals("TRADE_SUCCESS")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序
                HotelOrder hotelOrder = getInstance.getHotelOrder(out_trade_no);
                hotelOrder.setOrderStatus(2);
                hotelOrder.setTradeNo(trade_no);
                hotelOrder.setPayType(1);
                getInstance.updateTempStore(hotelOrder);
                //注意：
                //付款完成后，支付宝系统发送该交易状态通知
            }

            response.getWriter().println("success");

        }else {//验证失败
            response.getWriter().println("fail");

            //调试用，写文本函数记录程序运行情况是否正常
            //String sWord = AlipaySignature.getSignCheckContentV1(params);
            //AlipayConfig.logResult(sWord);
        }
    }
    @GetMapping("returnUrl")
    public void returnUrl(HttpServletRequest request,HttpServletResponse response) throws Exception {

        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            response.getWriter().println("trade_no:"+trade_no+"<br/>out_trade_no:"+out_trade_no+"<br/>total_amount:"+total_amount);
            HotelOrder hotelOrder = getInstance.getHotelOrder(out_trade_no);
            request.getRequestDispatcher("http://i47fee.natappfree.cc/biz/api/hotelorder/getpersonalorderinfo/"+hotelOrder.getId()).forward(request,response);
        }else {
            response.getWriter().println("验签失败");
        }
    }
}
